package com.sam.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

@Component
public class ThreadDemoServiceImpl {
    private static Logger logger = LoggerFactory.getLogger(ThreadDemoServiceImpl.class);

    @Autowired
    private ThreadPoolUtil threadPoolUtil;

    public void multThread(){
        CountDownLatch countDownLatch = new CountDownLatch(4);

        for (int xx = 0;xx<4;xx++){
            threadPoolUtil.asyncServiceExecutor().submit(new ThreadRunner(countDownLatch));
        }

        try {
            countDownLatch.await();
            logger.info("所有线程结束");
        } catch (Exception e) {
            logger.error("阻塞异常");
        }

        threadPoolUtil.shutdown();
    }

    private class ThreadRunner implements Callable<Integer> {
        private CountDownLatch countDownLatch;
        ThreadRunner(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }

        @Override
        public Integer call() throws Exception {
            Integer result = 0;
            try {
                logger.info("线程--> " + Thread.currentThread().getId() + " 开始");
                for (long i = 0;i < 10000;i++){
                    result++;
                }
                logger.info("线程--> " + Thread.currentThread().getId() + " 结束");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Long l = countDownLatch.getCount();
                countDownLatch.countDown();  // 这个不管是否异常都需要数量减,否则会被堵塞无法结束
            }
            return result;
        }
    }

}
